<template>
  <div>
    <div class="search">
      <input class="search-input" type="text" v-model="keyword" placeholder="请输入城市名或拼音" />
    </div>
    <div class="search-content" ref="searchList" v-show="searchListShow">
      <ul>
        <li class="search-item border-bottom"
          v-for="item of searchList"
          :key="item.id"
          @click="handleCityClick(item)"
        >{{item.name}}</li>
        <li v-show="hasNoData" class="search-item no-data">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      searchListShow: false,
      searchList: [],
      searchFlag: false
    }
  },
  computed: {
    hasNoData () {
      return this.searchList.length <= 0
    }
  },
  watch: {
    keyword () {
      // 避免多次触发
      if (this.searchFlag) { return }
      this.searchFlag = true
      setTimeout(() => {
        this.searchFlag = false
      }, 100)
      if (this.keyword !== '') { // 搜索框不为空
        this.searchListShow = true
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach(elem => {
            if (elem.spell.indexOf(this.keyword) > -1 || elem.name.indexOf(this.keyword) > -1) {
              result.push(elem)
            }
          })
        }
        this.searchList = result
      } else { // 搜索框为空
        this.searchList = []
        this.searchListShow = false
      }
    }
  },
  methods: {
    handleCityClick (city) {
      // this.$store.commit('changeCity', city)
      this.changeCity(city)
      this.$router.go(-1)
    },
    ...mapMutations(['changeCity'])
  },
  updated () {
    this.bscroll = new Bscroll(this.$refs.searchList, {click: true})
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .search
    height .72rem
    padding 0 .1rem
    background $bgColor
    .search-input
      padding 0 .16rem
      width 100%
      height .62rem
      line-height .62rem
      text-align .62rem
      border-radius .06rem
      color #666
      box-sizing border-box
  .search-content
    z-index 1
    overflow hidden
    position absolute
    top 1.58rem
    left 0
    right 0
    bottom 0
    background #eee
    .search-item
      padding-left .2rem
      line-height .76rem
      background #fff
    .no-data
      text-align center
      color #999
      font-size .24rem
</style>
